﻿using System;
using System.Data;
using System.IO;
using System.Text;

namespace Anthony.Library.Entensions
{
    public static class DataViewExtensions
    {

        /// <summary>
        /// Outputs the DataView to CSV
        /// </summary>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static string ToCSV(this DataView dv)
        {
            StringBuilder sb = new StringBuilder();

            //write out the columns
            for (int i = 0; i < dv.Table.Columns.Count; i++)
            {
                sb.Append(GetWriteableValue(dv.Table.Columns[i].ColumnName).Replace(Environment.NewLine, " "));
                if (i != dv.Table.Columns.Count - 1)
                    sb.Append(",");
            }
            sb.AppendLine();
            //write out the rows
            foreach (DataRowView dr in dv)
            {
                for (int i = 0; i < dv.Table.Columns.Count; i++)
                {
                    sb.Append(GetWriteableValue(dr[dv.Table.Columns[i].ColumnName]).Replace(Environment.NewLine, " "));
                    if (i != dv.Table.Columns.Count - 1)
                        sb.Append(",");
                }
                sb.AppendLine();
            }

            return sb.ToString();
        }

        /// <summary>
        /// Surround the value with double quotes if it contains a comma, line break or double quotes, and replace the double quotes with double double quotes.
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        private static string GetWriteableValue(object o)
        {
            if (o == null || o == Convert.DBNull)
                return string.Empty;
            else if ((o.ToString().IndexOf(",") == -1) &&
                    (o.ToString().IndexOf(Environment.NewLine) == -1) && (o.ToString().IndexOf("\n") == -1) &&
                    (o.ToString().IndexOf("\"") == -1) && (o.ToString().IndexOf("\f") == -1) && (o.ToString().IndexOf("\r") == -1))
                return o.ToString();
            else
                return "\"" + o.ToString().Replace("\"", "\"\"") + "\"";

        }

    }
}
